<?php
namespace app\common\model;

use think\facade\Db;
use think\facade\Cache;
use hema\wechat\Driver;
use hema\wechat\Pay;
use hema\wechat\Map;

/**
 * 用户认证申请模型
 */
class Apply extends BaseModel
{
    // 定义表名
    protected $name = 'apply';

    // 定义主键
    protected $pk = 'apply_id';

    // 追加字段
    protected $append = [
        'details'
    ];

    /**
     * 用户详情表
     */
    public function getDetailsAttr($value,$data)
    {
        return UserDetail::getDetail(['user_id' => $data['user_id']]);
    }

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\\common\\model\\User');
    }

    /**
     * 认证类型
     */
    public function getApplyModeAttr($value)
    {
        $status = [10 => '小程序申请', 20 => '商户入驻', 30 => '支付认证', 40 => '代理认证', 50 => '实名认证'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 认证类型
     */
    public function getAuthModeAttr($value)
    {
        $status = [10 => '工商', 20 => '个人'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 代理级别
     */
    public function getAgentModeAttr($value)
    {
        $status = [10 => '区县', 20 => '市级', 30 => '省级'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 付款状态
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款', 30 => '免费认证'];
        return ['text' => $status[$value], 'value' => $value];
    }

   /**
     * 当前申请状态
     */
    public function getApplyStatusAttr($value,$data)
    {
        //如果是微信支付申请单 并且是审核中 
        if($data['apply_mode'] == 30 and $value == 20 and !empty($data['business_code'])){
            $wxPay = new Pay;
            //查询审核状态
            if($result = $wxPay->queryApplyment($data['business_code'])){
                //编辑中
                if($result['applyment_state'] == 'APPLYMENT_STATE_EDITTING' and $data['applyment_state'] != 80){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 80,
                        'apply_status' => 40,
                        'apply_time' => time(),
                        'reject' => '提交申请发生错误导致，请尝试重新提交'
                    ]);
                    $value = 40;
                }
                //已驳回
                if($result['applyment_state'] == 'APPLYMENT_STATE_REJECTED' and $data['applyment_state'] != 20){
                    $reject = '';
                    for($n=1;$n<=sizeof($result['audit_detail']);$n++){
                        $n > 1 && $reject = $reject . '，';
                        $reject = $reject . $n . $result['audit_detail'][$n-1]['reject_reason'];
                    }
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 20,
                        'apply_status' => 40,
                        'apply_time' => time(),
                        'reject' => $reject
                    ]);
                    $value = 40;
                }
                //待账户验证
                if($result['applyment_state'] == 'APPLYMENT_STATE_TO_BE_CONFIRMED' and $data['applyment_state'] != 30){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 30
                    ]);
                }
                //待签约
                if($result['applyment_state'] == 'APPLYMENT_STATE_TO_BE_SIGNED' and $data['applyment_state'] != 40){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 40
                    ]);
                }
                //开通权限中
                if($result['applyment_state'] == 'APPLYMENT_STATE_SIGNING' and $data['applyment_state'] != 50){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 50
                    ]);
                }
                //商户入驻申请已完成
                if($result['applyment_state'] == 'APPLYMENT_STATE_FINISHED' and $data['applyment_state'] != 60){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 60,
                        'apply_status' => 30,
                        'apply_time' => time(),
                    ]);
                    $value = 30;
                }
                //申请单已被撤销
                if($result['applyment_state'] == 'APPLYMENT_STATE_CANCELED' and $data['applyment_state'] != 70){
                    $model = self::get($data['apply_id']);
                    $model->save([
                        'applyment_state' => 70,
                        'apply_status' => 40,
                        'apply_time' => time(),
                        'reject' => '申请单已被撤销，请重新申请'
                    ]);
                    $value = 40;
                }
            }
        }
        $status = [10 => '待审核', 20 => '验证中', 30 => '认证成功', 40 => '被驳回'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 官方平台申请状态
     */
    public function getApplymentStateAttr($value)
    {
        $status = [10 => '审核中', 20 => '已驳回', 30 => '待账户验证', 40 => '待签约', 50 => '开通权限中', 60 => '已完成', 70 => '已作废', 80 => '编辑中'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 获取认证申请列表
     */
    public function getList($apply_mode = 0, $user_id = 0, $agent_id = 0)
    {
        $filter = [];
        $apply_mode > 0 && $filter['apply_mode'] = $apply_mode;
        $user_id > 0 && $filter['user_id'] = $user_id;
        $agent_id > 0 && $filter['agent_id'] = $agent_id;
        // 执行查询
        return $this->with(['user'])
            ->where($filter)
            ->order('apply_id','desc')
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 详情
     */
    public static function detail($id)
    {
        return self::with(['user'])->find($id);
    }

    /**
     * 详情
     */
    public static function getApply(array $filter)
    {
        return self::with(['user'])->where($filter)->order('apply_id','desc')->find();
    }

    /**
     * 数据操作
     */
    public function action($data)
    {
        //更新商家资料
        if(isset($data['user_id'])){
            $user_id = $data['user_id'];
        }else{
           $user_id = $this->user_id; 
        }
        $model = new UserDetail;
        $model->action($data['details'],$user_id);
        //提交到微信审核
        if($data['apply_status'] == 20){
            //注册小程序
            if($data['apply_mode'] == 10){
                $wx = new Driver;
                $queryarr =[
                    'name' => $data['details']['merchant_name'],     //营业执照名称
                    'code' => $data['details']['license_number'], //统一社会信用代码
                    'code_type' => 1,   // 企业代码类型（1：统一社会信用代码， 2：组织机构代码，3：营业执照注册号）
                    'legal_persona_wechat' => $data['details']['legal_persona_wechat'], //所有人微信
                    'legal_persona_name' => $data['details']['id_card_name'],  //所有人姓名
                    'component_phone' => $data['details']['mobile_phone'] //第三方联系电话
                ];
                if(!$wx->registerMiniprogram($queryarr)){
                    $this->error = $wx->getError();
                    return false;
                }
            }
            //微信支付
            if($data['apply_mode'] == 30){
                $queryarr = $this->applyment($data);//格式化请求数据
                $wxPay = new Pay;
                if(!$result = $wxPay->applyment($queryarr)){
                    $this->error = $wxPay->getError();
                    return false;
                }
                $data['applyment_id'] = $result; //申请编号
            }
        }
        //判断是否为修改操作
        if($this->apply_id){
            //支付审核通过
            if($data['apply_status'] == 30 AND $data['apply_mode'] == 30){
                $setting = new Setting;
                if(!$setting->edit('wxpay',[
                    'app_id' => $data['app_id'], //微信应用
                    'is_sub' => 1, //是否为特约商户
                    'mch_id' => $data['details']['mch_id'],//商户号
                    'api_key' => '',//密钥
                    'cert_pem' => '', //apiclient_cert.pem 证书
                    'key_pem' => '' //apiclient_key.pem 密钥
                ],$this->applet_id)){
                    $this->error = '支付设置失败';
                    return false;
                }
            }
            //设置为代理
            if($data['apply_mode'] == 40 AND $data['apply_status'] == 30){
                User::where('user_id',$this->user_id)->update(['status' => 30]);
            }
        }else{
            //添加操作
            $data['pay_status'] = 30;//免费认证
            
            //如果是代理申请
            if($data['apply_mode'] == 40){
                $map = new Map;
                if(!$location = $map->getLocation($data['location'])){
                    $this->error = $map->getError();
                    return false;
                }
                $data['province'] = $location['province'];
                $data['city'] = $location['city'];
                $data['district'] = $location['district'];
            }
            //如果是申请小程序
            if($data['apply_mode'] == 10){
                /*
                $webpay = Setting::getItem('webpay',0);//获取站点支付配置
                //判断是否收费
                if($webpay['cost']['applet_fee'] > 0){
                    $user = User::withoutGlobalScope()->where('user_id',$data['user_id'])->find();
                    if($user['money'] < $webpay['cost']['applet_fee']){
                        $this->error = '账户余额不足￥' . $webpay['cost']['applet_fee'] . '元，请先充值';
                        return false;
                    }
    				//用户扣费
    				$money = $user['money'] - $webpay['cost']['applet_fee'];//计算扣除后的余额
    				$user->money = ['dec',$webpay['cost']['applet_fee']];
    				$user->score = ['inc',$webpay['cost']['applet_fee']]; //增加积分
    				$user->pay = ['inc',$webpay['cost']['applet_fee']]; //增加消费金额
    				$user->save();
    				//生成交易记录
                    $order_list = [];
                    $order_no = order_no();
    				array_push($order_list,[
    					'user_type' => 20,
    					'action' => 40,//扣减
    					'order_no' => $order_no,
    					'money' => $webpay['cost']['applet_fee'],
    					'remark' => '小程序审核费',
    					'user_id' => $data['user_id']
    				]);
    				array_push($order_list,[
    					'user_type' => 40, //平台
    					'action' => 50,//分红
    					'order_no' => $order_no,
    					'money' => $webpay['cost']['applet_fee'],
    					'remark' => '小程序审核费'
    				]);
    				//添加流水记录
    				$model = new Record;
    				$model->saveAll($order_list);
                    //账户资金变动提醒
                    sand_account_change_msg('小程序审核费',$webpay['cost']['applet_fee'],$money,$data['user_id']);
                    $data['pay_status'] = 20;//认证费已支付
                }*/
            }
            $data['pay_time'] = time();//付款时间 
        }
        return $this->save($data);
    }
    
    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();
    }
    
    /**
     * 特约商户进件
     */
    private function applyment($data)
    {
        $queryarr = [
            'business_code' => $data['business_code'],//业务申请编号
            'contact_info' => [   //超级管理员信息
                'contact_type' => 'LEGAL',//超级管理员类型 LEGAL=经营者/法人 UPER=经办人
                'contact_name' => $data['details']['id_card_name'],//（加密）超级管理员姓名
                'mobile_phone' => $data['details']['mobile_phone'],//（加密）联系手机
                'contact_email' => $data['details']['contact_email'],//（加密）联系邮箱
            ],
            'subject_info' => [   //主体资料
                'subject_type' => $data['details']['subject_type'],//主体类型 个体户=SUBJECT_TYPE_INDIVIDUAL 企业=SUBJECT_TYPE_ENTERPRISE
                'business_license_info' => [ //营业执照信息
                    'license_copy' => $data['details']['license_copy'],//营业执照照片MediaID
                    'license_number' => $data['details']['license_number'],//统一社会信用代码
                    'merchant_name' => $data['details']['merchant_name'],//营业执照上的商户名称
                    'legal_person' => $data['details']['id_card_name'],//个体户经营者/法人姓名
                ],
                'identity_info' => [ //经营者/法人身份证件信息
                    'id_doc_type' => 'IDENTIFICATION_TYPE_IDCARD',//证件类型（默认居民身份证）
                    'id_card_info' => [ //身份证信息
                        'id_card_copy' => $data['details']['id_card_copy'],//身份证人像面照片MediaID
                        'id_card_national' => $data['details']['id_card_national'],//身份证国徽面照片MediaID
                        'id_card_name' => $data['details']['id_card_name'],//（加密）身份证姓名
                        'id_card_number' => $data['details']['id_card_number'],//（加密）身份证号码
                        'id_card_address' => $data['details']['id_card_address'],//身份证居住地址，主体类型为企业时，需要填写
                        'card_period_begin' => $data['details']['card_period_begin'],//身份证有效期开始时间
                        'card_period_end' => $data['details']['card_period_end'],//身份证有效期结束时间
                    ],
                    'owner' => true,//经营者/法人是否为受益人 主体类型为企业时，需要填写
                ],
            ],
            'business_info' => [   //经营资料
                'merchant_shortname' => $data['details']['merchant_shortname'],//商户简称
                'service_phone' => $data['details']['mobile_phone'],//客服电话（商家的）
                'sales_info' => [ //经营场景
                    'sales_scenes_type' => [ //场景类型
                        'SALES_SCENES_MINI_PROGRAM',//小程序
                        'SALES_SCENES_STORE', //线下场所
                    ],
                    'biz_store_info' => [ //线下场所场景
                        'biz_store_name' => $data['details']['merchant_shortname'],//门店名称
                        'biz_address_code' => $data['details']['biz_address_code'],//门店所在省市编码
                        'biz_store_address' => $data['details']['biz_store_address'],//门店地址
                        'store_entrance_pic' => [ //门头照片MediaID
                            $data['details']['store_entrance_pic']
                        ],
                        'indoor_pic' => [ //店内照片MediaID
                            $data['details']['indoor_pic']
                        ],
                    ],
                    'mini_program_info' => [ //小程序场景
                        'mini_program_sub_appid' => $data['app_id'],//商家小程序APPID
                    ],
                ],
            ],
            'settlement_info' => [   //结算规则
                //'settlement_id' => 'aaaa',//入驻结算规则ID
                'qualification_type' => '餐饮',//指定行业名称
                'qualifications' => [//特殊资质图片
                    $data['details']['qualifications']    
                ],
            ],
            'bank_account_info' => [   //结算银行账户
                //'bank_account_type' => '',//账户类型 BANK_ACCOUNT_TYPE_CORPORATE=对公银行账户 
                //'account_name' => '',//（加密）开户名称
                'account_bank' => $data['details']['account_bank'],//开户银行
                'bank_address_code' => $data['details']['bank_address_code'],//开户银行省市编码
                'account_number' => $data['details']['account_number'],//（加密）银行账号
            ],
        ];
        //如果主体类型是个体 
        if($data['details']['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL'){
           $queryarr['bank_account_info']['bank_account_type'] = 'BANK_ACCOUNT_TYPE_PERSONAL';//账户类型=经营者个人银行卡
           $queryarr['bank_account_info']['account_name'] = $data['details']['id_card_name'];//账户名称
           $queryarr['settlement_info']['settlement_id'] = '719';//入驻结算规则ID
        }else{
            //为公司企业
            $queryarr['bank_account_info']['bank_account_type'] = 'BANK_ACCOUNT_TYPE_CORPORATE';//账户类型=对公银行账户
            $queryarr['bank_account_info']['account_name'] = $data['details']['merchant_name'];//账户名称
            $queryarr['settlement_info']['settlement_id'] = '716';//入驻结算规则ID
        }
        return $queryarr;
    }






















    /**
     * 详情
     */
    public static function getDetail($where = [])
    {
        return self::withoutGlobalScope()->where($where)->find();
    }
}
